<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { storeToRefs } from 'pinia';
import { guideInfo } from '@/app/guideInfo';
import { useUserInfoStore } from '@/app/globalStores/userInfo';
import { useApiStore } from '@/app/api/apiStore';
import { getPop } from '@/app/globalStores/uniqueComponents';
import { userTypeReadable } from './models/userTypeDisplay';
import { RouterLink } from 'vue-router';
import { useIdentitiesRoutesJump } from './routes/routesJump';
import { useLocalConfigStore } from '@/app/globalStores/localConfig';
import copy from 'copy-to-clipboard';
import { loginName, logoutName } from './routes/routesNames';

const props = defineProps<{
    backAfterSuccess?:string,
    logoutImmediatly?:boolean,
}>();
const router = useRouter()
const { loginExpireHrs } = storeToRefs(useLocalConfigStore())

const userName = ref<string>("")
const password = ref<string>("")
const setExpire = ref<boolean>(false);
const failedGuide = ref<string>();
const userInfoStore = useUserInfoStore()
const { userInfo } = storeToRefs(userInfoStore)
const api = useApiStore()
const pop = getPop()
const { registerRoute } = useIdentitiesRoutesJump()
const isDev = import.meta.env.DEV;

async function login(){
    const loginResp = await api.auth.login(
        userName.value,
        password.value,
        loginExpireHrs.value
    )
    if (loginResp) {
        userInfoStore.clearValue();
        await userInfoStore.getIdentityInfo(true);
        pop?.show("登录成功", "success");
        if (props.backAfterSuccess) {
            router.back()
        } else {
            router.push("/")
        }
    }else{
        const way = guideInfo.resetPassword || "请联系管理员重置"
        failedGuide.value = "如果忘记密码，" + way
    }
};
const route = useRoute()
async function logout() {
    api.clearJwtToken()
    userInfoStore.clearValue()
    pop?.show("已经成功退出登录","success");
    if(route.name == logoutName){
        router.push({name: loginName})
    }
}
function copyJwtToken(){
    const token = api.jwtToken;
    if(!token){
        pop?.show("无token", 'failed');
        return;
    }
    copy(token);
    pop?.show("已复制到剪切板", 'success');
}

const leftTimeDisplay = computed<string>(()=>{
    if(!userInfo){
        return '0小时';
    }
    const hours = userInfo.value?.leftHours ?? 0;
    if(hours>72){
        return Math.round(hours/24)+'天';
    }
    return hours+'小时';
})

watch(()=>props.logoutImmediatly, async()=>{
    if(props.logoutImmediatly){
        await logout();
        return;
    } 
})

onMounted(async()=>{
    if(props.logoutImmediatly){
        await logout();
        return; 
    }
    await userInfoStore.getIdentityInfo(true);
})
onUnmounted(()=>{
})
</script>

<template>
    <div>
        <h1>登录</h1>
    </div>
    <div>
        <table><tbody>
            <tr>
                <td>昵称</td>
                <td>
                    <input v-model="userName" type="text"/>
                </td>
            </tr>
            <tr>
                <td>密码</td>
                <td>
                    <input v-model="password" type="password"/>
                </td>
            </tr>
        </tbody></table>
        <div class="login">
            <button @click="login" class="confirm">登&nbsp;录</button>
        </div>
        <div class="needExpire">
            <div @click="setExpire=!setExpire" style="cursor: pointer;">登录状态保持</div>
            <select v-show="setExpire" v-model="loginExpireHrs">
                <option :value="3">3小时</option>
                <option :value="24">24小时</option>
                <option :value="168">7天</option>
                <option :value="720">30天</option>
                <option :value="8760">365天</option>
            </select>
        </div>
        <div v-show="setExpire" style="color:red; text-align: center;">仅在自己的设备上选择较长时间</div>
        <RouterLink class="register" :to="registerRoute()" v-if="false">
            注册账号 <!--TODO：设置是否允许自行注册-->
        </RouterLink>
        <div class="guide" style="color:red" v-if="failedGuide">{{ failedGuide }}</div>
    </div>
    <div class="loginInfo" v-if="userInfo && (userInfo.id??0)>0">
        当前登录：
        [{{ userTypeReadable(userInfo.type) }}]{{ userInfo.name }}<br/>
        登录有效期：{{ leftTimeDisplay }}<br/>
        <button @click="logout" class="logout">退出登录</button>
        <button v-if="isDev" @click="copyJwtToken" class="logOut">复制token</button>
    </div>
</template>

<style scoped lang="scss">
.guide{
    margin: 10px;
    text-align: center;
    border-radius: 5px;
}
table{
    margin:auto;
    background-color: transparent;
    font-size: large;
    color:gray
}
td{
    background-color: transparent;
}
input{
    background-color: #eee;
}
.needExpire{
    text-align: center;
    height: 60px;
    margin-top: 20px;
    font-size: small;
    color: #999;
    display: flex;
    justify-content: center;
    align-items: center;
    white-space: nowrap;
    flex-wrap: wrap;
}
.needExpire select{
    padding: 2px;
    margin: 2px;
    margin-left: 10px;
}
.login{
    display: flex;
    justify-content: center;
}
button.logout{
    background-color: gray;
    color:white;
    padding: 2px;
}
.footer{
    position: fixed;
    bottom: 0px;
    left: 0px;
    right: 0px;
}
.loginInfo{
    color:gray;
    font-size:small;
    text-align: center;
    position: fixed;
    margin: 0px;
    left:20px;
    bottom: 35px;
}
.register{
    display: block;
    text-align: center;
    color:gray;
    margin-top: 20px;
    font-size: 16px;
    text-decoration: underline;
    cursor: pointer;
}
</style>